<template>
  <div style="padding: 20px">
    <el-form
      ref="editPositionRef"
      :model="editPosition"
      label-width="120px"
      :rules="rules"
    >
      <el-divider content-position="left"><h3>基本信息</h3></el-divider>
      <el-form-item label="职位名称" prop="jobname">
        <el-input
          v-model="editPosition.jobname"
          placeholder=""
          style="width: 35%"
        ></el-input>
      </el-form-item>
      <el-form-item label="招聘状态" prop="isDisplay">
        <el-radio v-model="editPosition.isDisplay" :label="1">招聘中</el-radio>
        <el-radio v-model="editPosition.isDisplay" :label="0">已暂停</el-radio>
      </el-form-item>
      <el-form-item label="审核状态" prop="audit">
        <el-radio-group v-model="editPosition.audit">
          <el-radio :label="0">待审核</el-radio>
          <el-radio :label="1">已通过</el-radio>
          <el-radio :label="2">未通过</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="职位性质" prop="nature">
        <el-radio v-model="editPosition.nature" :label="1">全职</el-radio>
        <el-radio v-model="editPosition.nature" :label="2">实习</el-radio>
        <el-radio v-model="editPosition.nature" :label="3">兼职</el-radio>
      </el-form-item>
      <el-form-item label="职位类别" prop="category1">
        <el-cascader
          v-model="categoryArr"
          :options="positionType"
          @change="handleChange"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="学历要求" prop="education">
        <el-select
          v-model="editPosition.education"
          placeholder=""
          style="width: 35%"
        >
          <el-option
            v-for="item in jobExperience"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工作经验" prop="experience">
        <el-select
          v-model="editPosition.experience"
          placeholder=""
          style="width: 35%"
        >
          <el-option
            v-for="item in experienceList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="招聘人数" prop="amount">
            <el-input
              v-model.number="editPosition.amount"
              placeholder="若干"
            ></el-input>
      </el-form-item>
       <el-form-item label="薪资待遇" prop="minWage">
            <el-row :gutter="10" type="flex">
              <el-input
                v-model="editPosition.minWage"
                style="width: 20%; margin-right: 5px"
                :placeholder="
                  editPosition.negotiable ? editPosition.minWage : ''
                "
                :disabled="editPosition.negotiable"
              ></el-input>
              -
              <el-input
                v-model="editPosition.maxWage"
                style="width: 20%; margin-left: 5px"
                :placeholder="
                  editPosition.negotiable ? editPosition.maxWage : ''
                "
                :disabled="editPosition.negotiable"
              ></el-input>
            </el-row>
          </el-form-item>
      <el-form-item label="工作地区">
        <el-cascader
          v-model="workArea"
          :options="workingArea"
          @change="handleWorkAreaChange"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="工作地址" prop="address">
        <el-input
          v-model="editPosition.address"
          placeholder=""
          style="width: 35%"
        ></el-input>
      </el-form-item>
      <el-form-item label="职位描述" prop="content">
        <el-input
          v-model="editPosition.content"
          placeholder=""
          type="textarea"
          style="width: 35%"
          :rows="8"
        ></el-input>
      </el-form-item>
      <el-divider content-position="left"><h3>其他信息</h3></el-divider>
      <el-form-item label="岗位福利">
        <el-select 
          v-model="editPosition.tags" 
          multiple
          placeholder="请选择岗位福利" 
          style="width: 35%"
          :multiple-limit="10"
        >
          <el-option
            v-for="item in tags"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <el-button
          type="text"
          class="clear-btn"
          @click="clearTags"
          v-if="editPosition.tags && editPosition.tags.length"
        >
          清空
        </el-button>
      </el-form-item>
      <el-divider content-position="left"><h3>联系方式</h3></el-divider>
      <el-form-item label="联系方式" prop="useCompanyContact">
        <el-select
          v-model="editPosition.useCompanyContact"
          placeholder="使用企业资料联系方式"
        >
          <el-option
            v-for="item in useCompanyContactList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="联系人"
        prop="contact"
        v-if="editPosition.useCompanyContact === 0"
      >
        <el-input
          v-model="editPosition.contact"
          placeholder="请填写联系人"
          style="width: 35%"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="联系手机"
        prop="mobile"
        v-if="editPosition.useCompanyContact === 0"
      >
        <el-input
          v-model="editPosition.mobile"
          placeholder="请填写手机号"
          style="width: 35%"
          @input="handleMobileInput"
        ></el-input>
        <el-checkbox
          v-model="editPosition.needNotice"
          label="不对外显示仅接收通知"
          style="margin-left: 10px"
        ></el-checkbox>
      </el-form-item>
      <el-form-item
        label="企业固话"
        prop="telephone"
        v-if="editPosition.useCompanyContact === 0"
      >
        <el-input
          v-model="editPosition.telephone"
          placeholder="请输入联系固话(格式:区区号+电话号)"
          style="width: 35%"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="联系微信"
        prop="weixin"
        v-if="editPosition.useCompanyContact === 0"
      >
        <el-input
          v-model="editPosition.weixin"
          placeholder="请填写微信号"
          style="width: 35%"
        ></el-input>
        <el-checkbox
          v-model="weixinSameAsMobile"
          label="同手机号"
          style="margin-left: 10px"
          @change="handleWeixinSameAsMobile"
        ></el-checkbox>
      </el-form-item>
      <el-form-item
        label="联系邮箱"
        prop="email"
        v-if="editPosition.useCompanyContact === 0"
      >
        <el-input
          v-model="editPosition.email"
          placeholder="请输入邮箱号"
          style="width: 35%"
        ></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-checkbox v-model="editPosition.isSecrecy">
          联系方式保密（不想受到骚扰）
        </el-checkbox>
      </el-form-item>
      <el-form-item label="接收通知">
        <el-switch v-model="value1" active-text="按月付费"></el-switch>
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary" @click="savePosition">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  selCategoryTradeListApi,
  selCategoryDistrictListApi,
  selCategoryJobListApi,
  updatePositionByIdApi,
  selTagListApi,
} from "@/api/client";
export default {
  data() {
    return {
      value: true,
      // 职位类别
      categoryArr: [],
      // 工作地区
      workArea: [],
      // 编辑表单
      editPosition: {
        companyId: "",
        id: "",
        uid: "",
        address: "",
        ageNa: "",
        amount: "",
        category1: "",
        category2: "",
        category3: "",
        citycategoryArr: [],
        contact: "",
        content: "",
        customField1: "",
        customField2: "",
        customField3: "",
        department: "",
        district1: "",
        district2: "",
        district3: "",
        education: null,
        email: "",
        experience: null,
        isDisplay: null,
        isSecrecy: null,
        jobcategoryArr: [],
        jobFairId: "",
        jobname: "",
        mapLat: "",
        mapLng: "",
        mapZoom: "",
        maxAge: null,
        maxWage: null,
        minAge: null,
        minWage: null,
        mobile: "",
        nature: null,
        needNotice: null,
        negotiable: null,
        qq: "",
        source: "",
        tags: [],
        telephone: "",
        useCompanyContact: "",
        weixin: "",
      },
      // 工作类别
      positionType: [],
      // 学历要求
      jobExperience: [
        { value: 0, label: "不限学历" },
        { value: 1, label: "初中" },
        { value: 2, label: "高中" },
        { value: 3, label: "中技" },
        { value: 4, label: "中专" },
        { value: 5, label: "大专" },
        { value: 6, label: "本科" },
        { value: 7, label: "硕士" },
        { value: 8, label: "博士" },
        { value: 9, label: "博士后" },
      ],
      // 工作经验
      experienceList: [
        { value: 0, label: "不限工作经验" },
        { value: 1, label: "应届生" },
        { value: 2, label: "1年" },
        { value: 3, label: "2年" },
        { value: 4, label: "3年" },
        { value: 5, label: "3-5年" },
        { value: 6, label: "5-10年" },
      ],
      // 最小薪资
      minWageList: [
        { value: 500, label: "500元/月" },
        { value: 1000, label: "1000元/月" },
        { value: 1500, label: "1500元/月" },
        { value: 2000, label: "2000元/月" },
        { value: 2500, label: "2500元/月" },
        { value: 3000, label: "3000元/月" },
        { value: 3500, label: "3500元/月" },
        { value: 4000, label: "4000元/月" },
        { value: 4500, label: "4500元/月" },
        { value: 5000, label: "5000元/月" },
        { value: 5500, label: "5500元/月" },
        { value: 6000, label: "6000元/月" },
        { value: 6500, label: "6500元/月" },
        { value: 7000, label: "7000元/月" },
        { value: 7500, label: "7500元/月" },
        { value: 8000, label: "8000元/月" },
        { value: 8500, label: "8500元/月" },
        { value: 9000, label: "9000元/月" },
        { value: 9500, label: "9500元/月" },
        { value: 10000, label: "10000元/月" },
        { value: 10500, label: "10500元/月" },
        { value: 11000, label: "11000元/月" },
        { value: 11500, label: "11500元/月" },
        { value: 12000, label: "12000元/月" },
        { value: 12500, label: "12500元/月" },
        { value: 13000, label: "13000元/月" },
        { value: 13500, label: "13500元/月" },
        { value: 14000, label: "14000元/月" },
        { value: 14500, label: "14500元/月" },
        { value: 15000, label: "15000元/月" },
        { value: 20000, label: "20000元/月" },
        { value: 25000, label: "25000元/月" },
        { value: 30000, label: "30000元/月" },
        { value: 35000, label: "35000元/月" },
        { value: 40000, label: "40000元/月" },
        { value: 45000, label: "45000元/月" },
      ],
      // 最大薪资
      maxWageList: [
        { value: 1000, label: "1000元/月" },
        { value: 1500, label: "1500元/月" },
        { value: 2000, label: "2000元/月" },
        { value: 2500, label: "2500元/月" },
        { value: 3000, label: "3000元/月" },
        { value: 3500, label: "3500元/月" },
        { value: 4000, label: "4000元/月" },
        { value: 4500, label: "4500元/月" },
        { value: 5000, label: "5000元/月" },
        { value: 5500, label: "5500元/月" },
        { value: 6000, label: "6000元/月" },
        { value: 6500, label: "6500元/月" },
        { value: 7000, label: "7000元/月" },
        { value: 7500, label: "7500元/月" },
        { value: 8000, label: "8000元/月" },
        { value: 8500, label: "8500元/月" },
        { value: 9000, label: "9000元/月" },
        { value: 9500, label: "9500元/月" },
        { value: 10000, label: "10000元/月" },
        { value: 10500, label: "10500元/月" },
        { value: 11000, label: "11000元/月" },
        { value: 11500, label: "11500元/月" },
        { value: 12000, label: "12000元/月" },
        { value: 12500, label: "12500元/月" },
        { value: 13000, label: "13000元/月" },
        { value: 13500, label: "13500元/月" },
        { value: 14000, label: "14000元/月" },
        { value: 14500, label: "14500元/月" },
        { value: 15000, label: "15000元/月" },
        { value: 20000, label: "20000元/月" },
        { value: 25000, label: "25000元/月" },
        { value: 30000, label: "30000元/月" },
        { value: 35000, label: "35000元/月" },
        { value: 40000, label: "40000元/月" },
        { value: 45000, label: "45000元/月" },
        { value: 50000, label: "50000元/月" },
      ],
      // 存储工作地区下拉
      selectedWorkArea: [],
      // 工作地区
      workingArea: [],
      weixinSameAsMobile: true,
      useCompanyContactList: [
        { label: "使用企业资料联系方式", value: 1 },
        { label: "使用其他联系方式", value: 0 },
      ],
      rules: {
        jobname: [
          { required: true, message: "请输入职位名称", trigger: "blur" },
        ],
        isDisplay: [
          { required: true, message: "请选择招聘状态", trigger: "blur" },
        ],
        audit: [
          { required: true, message: "请选择审核状态", trigger: "change" },
        ],
        nature: [
          { required: true, message: "请选择职位性质", trigger: "change" },
        ],
        jobcategoryArr: [
          { required: true, message: "请选择职位类别", trigger: "change" },
        ],
        education: [
          { required: true, message: "请选择学历要求", trigger: "change" },
        ],
        experience: [
          { required: true, message: "请选择工作经验", trigger: "change" },
        ],
        minWage: [
          { required: true, message: "请选择最小薪资", trigger: "change" },
        ],
        maxWage: [
          { required: true, message: "请选择最大薪资", trigger: "change" },
        ],
        address: [
          { required: true, message: "请输入工作地址", trigger: "blur" },
        ],
        mobile: [
          {
            required: true,
            message: "请填写联系手机",
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (this.editPosition.useCompanyContact === 0 && !value) {
                callback(new Error("请填写联系手机"));
              } else {
                callback();
              }
            },
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (
                this.editPosition.useCompanyContact === 0 &&
                value &&
                !/^1[3-9]\d{9}$/.test(value)
              ) {
                callback(new Error("请输入正确的手机号码"));
              } else {
                callback();
              }
            },
          },
        ],
        contact: [
          {
            required: true,
            message: "请填写联系人",
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (this.editPosition.useCompanyContact === 0 && !value) {
                callback(new Error("请填写联系人"));
              } else {
                callback();
              }
            },
          },
          {
            min: 2,
            max: 20,
            message: "联系人长度在2-20个字符之间",
            trigger: "blur",
          },
        ],
        district1: [
          { required: true, message: "请选择工作地区", trigger: "change" },
        ],
        district2: [
          { required: true, message: "请选择工作地区", trigger: "change" },
        ],
        district3: [
          { required: true, message: "请选择工作地区", trigger: "change" },
        ],
      },
      // 添加标签列表数组
      tags: [],
    };
  },
  async created() {
    // 先获取标签列表
    await this.selTagList();

    // 获取职位数据并处理地区回显
    const row = JSON.parse(localStorage.getItem("editPosition"));
    this.editPosition = row;

    // 处理地区回显
    if (this.editPosition.district3 === 0) {
      this.workArea = [
        this.editPosition.district1,
        this.editPosition.district2,
      ];
    } else {
      this.workArea = [
        this.editPosition.district1,
        this.editPosition.district2,
        this.editPosition.district3,
      ];
    }

    // 处理标签回显
    if (this.editPosition.tags && this.editPosition.tags.length > 0) {
      // 将字符串数组转换为id数组
      const matchedTags = this.tags
        .filter((tag) => this.editPosition.tags.includes(tag.id))
        .map((tag) => tag.id);

      this.editPosition.tags = matchedTags;
    }

    this.categoryArr = [
      this.editPosition.category1,
      this.editPosition.category2,
      this.editPosition.category3,
    ];
    this.selCategoryJobList();
    this.selCategoryDistrictList();
  },
  methods: {
    // 选择最小薪资改变
    updateMinWageList(value) {
      if (this.editPosition.minWage === null) {
        // 如果没有选择最小薪资，清空最大薪资列表
        this.maxWageList = [];
      } else {
        console.log(value);
        this.editPosition.minWage = value;
        // 根据选择的最小薪资更新最大薪资列表
        this.maxWageList = this.minWageList.filter(
          (item) => item.value > this.editPosition.minWage + 500
        );
      }
    },
    // 选择最大薪资改变
    updateMaxWageList(value) {
      console.log(value);
      this.editPosition.maxWage = value;
    },
    // 工作地区改变得时候
    handleWorkAreaChange(value) {
      if (value && value.length > 0) {
        this.editPosition.district1 = value[0] || "";
        this.editPosition.district2 = value[1] || "";
        this.editPosition.district3 = value[2] || 0;
      }
    },
    // 管理工作地区
    async selCategoryDistrictList() {
      const res = await selCategoryDistrictListApi();
      console.log(res);
      // console.log(res.data[0]);
      this.workingArea = res.data[0].map((item) => ({
        label: item.name, // 父级项的 value 设置为 name
        value: item.id,
        children: item.children
          ? item.children.map((child) => ({
              label: child.name, // 子项的 label 设置为 name
              value: child.id, // 子项的 value 设置为 id 的字符串形式
              children: child.children.map((subDistrict) => ({
                label: subDistrict.name, // 父级项的 value 设置为 name
                value: subDistrict.id,
              })),
            }))
          : [],
      }));
      console.log(this.workingArea);
    },
    // 管理职位类型查询
    async selCategoryJobList() {
      const res = await selCategoryJobListApi();
      this.positionType = res.data[0].map((item) => ({
        label: item.name, // 父级项的 value 设置为 name
        value: item.id,
        children: item.children
          ? item.children.map((child) => ({
              label: child.name, // 子项的 label 设置为 name
              value: child.id, // 子项的 value 设置为 id 的字符串形式
              children: child.children.map((subDistrict) => ({
                label: subDistrict.name, // 父级项的 value 设置为 name
                value: subDistrict.id,
              })), // 子项的 children 默认为空数组，如果需要更深层次的数据结构，可以在这里添加逻辑
            }))
          : [], // 如果没有 categoryDistricts，children 设置为空数组
      }));
      console.log(this.positionType);
    },
    async savePosition() {
      this.$refs.editPositionRef.validate(async (valid) => {
        if (valid) {
          const requestData = {
            companyId: this.editPosition.companyId,
            id: this.editPosition.id,
            uid: this.editPosition.uid,
            address: this.editPosition.address,
            ageNa: this.editPosition.ageNa,
            amount: this.editPosition.amount,
            category1: this.editPosition.category1,
            category2: this.editPosition.category2,
            category3: this.editPosition.category3,
            citycategoryArr: this.editPosition.citycategoryArr,
            contact: this.editPosition.contact,
            content: this.editPosition.content,
            customField1: this.editPosition.customField1,
            customField2: this.editPosition.customField2,
            customField3: this.editPosition.customField3,
            department: this.editPosition.department,
            district1: this.editPosition.district1,
            district2: this.editPosition.district2,
            district3: this.editPosition.district3,
            education: this.editPosition.education,
            email: this.editPosition.email,
            experience: this.editPosition.experience,
            isDisplay: this.editPosition.isDisplay,
            isSecrecy: this.editPosition.isSecrecy,
            jobcategoryArr: this.editPosition.jobcategoryArr,
            jobFairId: this.editPosition.jobFairId,
            jobname: this.editPosition.jobname,
            mapLat: this.editPosition.mapLat,
            mapLng: this.editPosition.mapLng,
            mapZoom: this.editPosition.mapZoom,
            maxAge: this.editPosition.maxAge,
            maxWage: this.editPosition.maxWage,
            minAge: this.editPosition.minAge,
            minWage: this.editPosition.minWage,
            mobile: this.editPosition.mobile,
            nature: this.editPosition.nature,
            needNotice: this.editPosition.needNotice,
            negotiable: this.editPosition.negotiable,
            qq: this.editPosition.qq,
            source: this.editPosition.source,
            tags: this.editPosition.tags,
            telephone: this.editPosition.telephone,
            useCompanyContact: this.editPosition.useCompanyContact,
            weixin: this.editPosition.weixin,
            weixinSameAsMobile: Number(this.weixinSameAsMobile),
          };

          try {
            const res = await updatePositionByIdApi(requestData);
            if (res.code === 1) {
              this.$message.success("保存成功");
              this.$router.back();
            } else {
              this.$message.error(res.message || "保存失败");
            }
          } catch (error) {
            this.$message.error("保存失败：" + error.message);
          }
        } else {
          this.$message.error("请完善信息");
          return false;
        }
      });
    },
    handleMobileInput(value) {
      if (this.weixinSameAsMobile) {
        this.editPosition.weixin = value;
      }
    },
    handleWeixinSameAsMobile(checked) {
      if (checked) {
        this.editPosition.weixin = this.editPosition.mobile;
      }
    },
    // 添加标签查询方法
    async selTagList() {
      try {
        const res = await selTagListApi();
        if(res.code === 1) {
          this.tags = res.data;
          console.log('获取到的标签列表:', this.tags);
        } else {
          this.$message.error('获取福利标签失败');
        }
      } catch(error) {
        console.error('获取福利标签出错:', error);
        this.$message.error('获取福利标签失败');
      }
    },
    // 清空所有标签
    clearTags() {
      this.editPosition.tags = [];
    },
  },
  computed: {
    // 添加已选标签计算属性
    selectedTags() {
      return this.tags.filter((tag) => this.editPosition.tags.includes(tag.id));
    },
  },
};
</script>

<style lang="scss" scoped>
el-divider {
  margin: 40px 0;
}

.clear-btn {
  color: #409eff;
  margin-left: 10px;
}

:deep(.el-select) {
  width: 35%;
}

:deep(.el-tag) {
  background-color: #f4f4f5;
  border-color: #e9e9eb;
  color: #909399;
  margin-right: 8px;
  margin-bottom: 8px;
}
</style>
